package online.westonline.com.westonline.ui;

import android.support.design.widget.TextInputEditText;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.easy.west.westclient.api.login.bean.User;
import com.easy.west.westclient.api.login.event.LoginEvent;
import com.jaeger.library.StatusBarUtil;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.im.android.api.JMessageClient;
import cn.jpush.im.android.api.options.RegisterOptionalUserInfo;
import cn.jpush.im.api.BasicCallback;
import online.westonline.com.westonline.MyApplication;
import online.westonline.com.westonline.R;
import online.westonline.com.westonline.base.BaseActivity;
import online.westonline.com.westonline.utils.CacheUtils;
import online.westonline.com.westonline.utils.ToastUtils;

public class LoginActivity extends BaseActivity {



    @BindView(R.id.edit_username)
    TextInputEditText editUsername;
    @BindView(R.id.edit_username_layout)
    TextInputLayout editUsernameLayout;
    @BindView(R.id.edit_password)
    TextInputEditText editPassword;
    @BindView(R.id.edit_password_layout)
    TextInputLayout editPasswordLayout;
    @BindView(R.id.btn_login)
    Button btnLogin;
    @BindView(R.id.checkbox_remenber_password)
    CheckBox checkboxRemenberPassword;
    @BindView(R.id.img_logo)
    ImageView tvLogo;
    @BindView(R.id.li_login_layout)
    LinearLayout liLoginLayout;
    @BindView(R.id.tv_more)
    TextView tvMore;
    private boolean isswitch=false;
    private User user;
    //是不是极光im里的新人
    private boolean isImFirst = false;
    @Override
    protected void initview() {
        //状态栏为半透明
        StatusBarUtil.setTranslucent(this, 125);
        //startService(new Intent(this, FloatViewService.class));
        openWindow();
        //申请悬浮窗权限
        //askWindowPerMisson();
        //设置事件
        initsessin();
    }

    /**
     * 打开悬浮窗(测试)
     */
    private void openWindow() {
        /*
        //去加载view
        FloatWindow.with(MyApplication.getContext())
                .setView(R.layout.float_view)
                .setWidth(100)
                .setHeight(Screen.width,0.3f)
                .setX(100)                                   //设置控件初始位置
                .setY(Screen.height,0.1f)
                .setDesktopShow(true)
                .setMoveType(MoveType.slide)
                .build();
                */

    }


    private void initsessin() {
        //配置选中框
        checkboxRemenberPassword.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                CacheUtils.getInstance().remberPasswordCheck(isChecked);
            }
        });
        //配置登录窗口
        btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String username = editUsername.getText().toString();
                String password = editPassword.getText().toString();
                if (TextUtils.isEmpty(username)) {
                    editUsernameLayout.setError("请输入用户名");
                    return;
                }
                if (TextUtils.isEmpty(password)) {
                    editPasswordLayout.setError("请输入密码");
                    return;
                }
                //请求,提交
                if (checkboxRemenberPassword.isChecked()) {
                    if (isswitch)
                    {
                        CacheUtils.getInstance().remberUserAndPasswordByMisu(username,password);
                        return;
                    }
                    CacheUtils.getInstance().remberUserAndPassword(username, password);
                }
                MyApplication.getClient().login(username, password);
                showProgessDialog("登录中");
            }
        });

    }

    @Override
    protected void initdata() {
        //保留某个activity
        MyApplication.exitExcpetActivity(LoginActivity.class.getSimpleName());
        //设置checkBox状态
        checkboxRemenberPassword.setChecked(CacheUtils.getInstance().getPasswordCheckValue());
        //载入已经储存的用户名和密码
        editPassword.setText(CacheUtils.getInstance().password() == null ? "" : CacheUtils.getInstance().password());
        editUsername.setText(CacheUtils.getInstance().getUserName() == null ? "" : CacheUtils.getInstance().getUserName());

    }

    @Override
    protected int setlayout() {
        return R.layout.activity_login;
    }


    /**
     * 普通用户登录
     * @param eva
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void login(LoginEvent eva) {
        if (eva.isOk()) {
            user = eva.getBean();
            if (user.getStatus() != 1) {
                ToastUtils.showToast("登录失败,用户名或密码错误");
                dissmissDialog();
                return;
            }
            CacheUtils.getInstance().saveUser(user);
            LoginIm();


        } else {
            ToastUtils.showToast(eva.getCodeDescribe());
            dissmissDialog();
        }
    }

    /***
     * IM登录状态的检查
     */
    private void LoginIm()
    {
        JMessageClient.login(user.getData().getAccess_token(), CacheUtils.getInstance().password(),
                new BasicCallback() {
                    @Override
                    public void gotResult(int i, String s) {
                        Log.e("登录信息",i+":"+s);
                        if (i==0)
                        {
                            dissmissDialog();
                            //设置别名
                            //1.当前域
                            //2.用户序列号(相当于key)
                            //3.别名为user的token
                            JPushInterface.setAlias(getApplicationContext(),user.getData().getId(),user.getData().getAccess_token());
                            if (isImFirst)
                            {
                                //前往初始头像设置界面
                                startActivity(AvatorActivity.class,true);
                            }
                            else
                            {
                                //0即登录成功
                                startActivity(HomeActivity.class,true);
                            }

                        }
                        else
                        {
                            switch (i)
                            {
                                case 871303:
                                    //用户名错误
                                    ToastUtils.showToast("您的用户名错误");
                                    dissmissDialog();
                                    break;
                                case 871304:

                                    ToastUtils.showToast("您的密码错误");
                                    dissmissDialog();
                                    break;
                                case  801004:
                                    //密码错误
                                    ToastUtils.showToast("您的密码错误");
                                    dissmissDialog();
                                    break;
                                case 801003:
                                    //用户不存在
                                    registim();
                                    break;
                                case 801006:
                                    dissmissDialog();
                                    //账号已被封禁
                                    showSelectDialog("提示","此账号已被封禁",null,null);
                                    break;
                                default:
                                    registim();
                                    break;
                            }
                        }
                    }
                });
    }

    /***
     * 注册极光im
     */
    private void registim() {
        //确定是了
        RegisterOptionalUserInfo userInfo = new RegisterOptionalUserInfo();
        userInfo.setNickname(user.getData().getName());
        JMessageClient.register(user.getData().getAccess_token(), CacheUtils.getInstance().password(),userInfo, new BasicCallback() {
            @Override
            public void gotResult(int i, String s) {
                if (i==0)
                {
                    isImFirst = true;
                    //成功,调用登录
                    LoginIm();
                }
                else
                {
                    switch (i)
                    {
                        case 871305:
                            ToastUtils.showToast("用户名不能低于4位,请联系管理员重新添加账号");
                            break;
                        default:
                            ToastUtils.showToast("错误:"+s);
                            break;
                    }
                }
            }
        });
    }



}

